/**
 * Document : LoginLogoutController Created on : 01/12/2012, 04:30:43 PM Author : rv
 *
 */
package edu.upc.embajada.controller;

import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles and retrieves the login or denied page depending on the URI template
 */
@Controller
public class LoginLogoutController {

    protected static Logger logger = Logger.getLogger("controller");

    /**
     * Handles and retrieves the login JSP page
     *
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/auth/login", method = RequestMethod.GET)
    public String getLoginPage(@RequestParam(value = "error", required = false) boolean error,
            ModelMap model) {
        logger.debug("request para el login page");

        // Add an error message to the model if login is unsuccessful
        // The 'error' parameter is set to true based on the when the authentication has failed. 
        // We declared this under the authentication-failure-url attribute inside the spring-security.xml
		/* See below:
         <form-login 
         login-page="/krams/auth/login" 
         authentication-failure-url="/krams/auth/login?error=true" 
         default-target-url="/krams/main/common"/>
         */
        if (error == true) {
            // Assign an error message
            model.put("error", "El usuario y password no son correctos!");
        } else {
            model.put("error", "");
        }

        return "auth/login";
    }

    /**
     * Handles and retrieves the denied JSP page. This is shown whenever a regular user tries to access an admin only page.
     *
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/auth/denied", method = RequestMethod.GET)
    public String getDeniedPage() {
        logger.debug("request para la denied page");

        // This will resolve to /WEB-INF/jsp/deniedpage.jsp
        return "auth/denied";
    }

    // hago que el Spring Security direccione aquí luego del login y
    // en base al rol, direcciono a la página de inicio correcta
    @RequestMapping("/default")
    public String defaultAfterLogin(HttpServletRequest request) {
        if (request.isUserInRole("ROLE_ADMIN")) {
            return "redirect:/pages/admin/consultarUsers";
        }
        return "redirect:/pages/visa/consultar";
    }
}